﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Diagnostics;
using System.Text;
using AdvancedSharpAdbClient.DeviceCommands;
using AdvancedSharpAdbClient;
using AdvancedSharpAdbClient.Models;
using AdvancedSharpAdbClient.Receivers;
using PaddleOCRSharp;


namespace AdbWpfDemo
{
    public partial class MainWindow : Window
    {
        private AdbClient client = new AdbClient();
        // 已连接设备列表，刷新时填充
        private List<DeviceData> devices = new List<DeviceData>();
        // 用于刷抖音任务的取消令牌源
        private CancellationTokenSource douyinCts = null;
        public MainWindow()
        {
            InitializeComponent();
            if (!AdbServer.Instance.GetStatus().IsRunning)
            {
                AdbServer server = new AdbServer();
                StartServerResult result = server.StartServer(@"C:\Program Files (x86)\Android\android-sdk\platform-tools\adb.exe", false);
                if (result != StartServerResult.Started)
                {
                    Console.WriteLine("Can't start adb server");
                }
            }
            RefreshDeviceList();
        }

        /// <summary>
        /// 刷新设备列表并更新 ComboBox
        /// </summary>
        private void RefreshDeviceList()
        {
            try
            {
                devices = client.GetDevices().ToList();
                cbDevices.Items.Clear();
                foreach (var device in devices)
                {
                    cbDevices.Items.Add(device.Serial);
                }
                if (devices.Count > 0)
                    cbDevices.SelectedIndex = 0;
                txtOutput.AppendText("设备列表已刷新。" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("刷新设备失败：" + ex.Message + Environment.NewLine);
            }
        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            RefreshDeviceList();
        }

        /// <summary>
        /// 获取选中设备的电量信息
        /// </summary>
        private async void btnBattery_Click(object sender, RoutedEventArgs e)
        {
            if (cbDevices.SelectedItem == null)
            {
                MessageBox.Show("请先选择一个设备。");
                return;
            }

            string serial = cbDevices.SelectedItem.ToString();
            DeviceData device = devices.FirstOrDefault(d => d.Serial == serial);
            if (device == null)
            {
                txtOutput.AppendText("未找到设备 " + serial + Environment.NewLine);
                return;
            }

            try
            {
                string command = "dumpsys battery";
                var receiver = new ConsoleOutputReceiver();
                await Task.Run(() =>
                {
                    client.ExecuteRemoteCommand(command, device, receiver);
                });
                string output = receiver.ToString();
                txtOutput.AppendText("电量信息：" + Environment.NewLine + ParseBatteryInfo(output) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("获取电量信息失败：" + ex.Message + Environment.NewLine);
            }
        }

        /// <summary>
        /// 简单解析电量信息，提取电量等级
        /// </summary>
        private string ParseBatteryInfo(string info)
        {
            var match = Regex.Match(info, @"level:\s*(\d+)");
            if (match.Success)
            {
                return "电量：" + match.Groups[1].Value + "%";
            }
            return "无法解析电量信息。";
        }

        /// <summary>
        /// 获取照片列表，并填充到 ListBox 中
        /// </summary>
        private async void btnGetPhotos_Click(object sender, RoutedEventArgs e)
        {
            if (cbDevices.SelectedItem == null)
            {
                MessageBox.Show("请先选择一个设备。");
                return;
            }
            string serial = cbDevices.SelectedItem.ToString();
            DeviceData device = devices.FirstOrDefault(d => d.Serial == serial);
            if (device == null)
            {
                txtOutput.AppendText("未找到设备 " + serial + Environment.NewLine);
                return;
            }

            try
            {
                string folder = "/sdcard/DCIM/Camera/";
                string command = "ls " + folder;
                var receiver = new ConsoleOutputReceiver();
                await Task.Run(() =>
                {
                    client.ExecuteRemoteCommand(command, device, receiver);
                });
                string output = receiver.ToString();
                txtOutput.AppendText("照片列表获取成功。" + Environment.NewLine);

                // 将结果按行解析并填充至 ListBox
                lbPhotos.Items.Clear();
                string[] files = output.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string file in files)
                {
                    lbPhotos.Items.Add(file.Trim());
                }
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("获取照片列表失败：" + ex.Message + Environment.NewLine);
            }
        }
        /// <summary>
        /// 截图
        /// </summary>
        private async void btnGetScreen_Click(object sender, RoutedEventArgs e)
        {
            if (cbDevices.SelectedItem == null)
            {
                MessageBox.Show("请先选择一个设备。");
                return;
            }
            string serial = cbDevices.SelectedItem.ToString();
            DeviceData device = devices.FirstOrDefault(d => d.Serial == serial);
            if (device == null)
            {
                txtOutput.AppendText("未找到设备 " + serial + Environment.NewLine);
                return;
            }

            try
            {
                var filename = $"screenshot{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png";
                var receiver = new ConsoleOutputReceiver();
                await Task.Run(() =>
                {
                    var command = $"screencap -p /sdcard/"+ filename;
                    client.ExecuteRemoteCommand(command, device, receiver);
                    
                });
                string output = receiver.ToString();
                txtOutput.AppendText("截图成功。" + Environment.NewLine);
                string localDir = AppDomain.CurrentDomain.BaseDirectory;
                string localPath = Path.Combine(localDir, filename);
                // 拉取文件到本地
                using (var sync = new SyncService(device))
                using (var stream = File.Create(localPath))
                {
                    sync.Pull("/sdcard/"+ filename, stream, null,false);
                }
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("截图失败：" + ex.Message + Environment.NewLine);
            }
        }

        /// <summary>
        /// 拍照操作：先启动相机应用，延时后发送快门命令
        /// </summary>
        private async void btnTakePhoto_Click(object sender, RoutedEventArgs e)
        {
            if (cbDevices.SelectedItem == null)
            {
                MessageBox.Show("请先选择一个设备。");
                return;
            }
            string serial = cbDevices.SelectedItem.ToString();
            DeviceData device = devices.FirstOrDefault(d => d.Serial == serial);
            if (device == null)
            {
                txtOutput.AppendText("未找到设备 " + serial + Environment.NewLine);
                return;
            }

            try
            {
                // 启动相机应用
                string commandOpenCamera = "am start -a android.media.action.STILL_IMAGE_CAMERA";
                var receiverOpen = new ConsoleOutputReceiver();
                await Task.Run(() =>
                {
                    client.ExecuteRemoteCommand(commandOpenCamera, device, receiverOpen);
                });
                txtOutput.AppendText("相机应用已启动，等待打开..." + Environment.NewLine);

                // 延时等待相机应用稳定
                await Task.Delay(3000);

                // 发送拍照命令（模拟快门按键）
                string commandTakePhoto = "input keyevent 27";
                var receiverTake = new ConsoleOutputReceiver();
                await Task.Run(() =>
                {
                    client.ExecuteRemoteCommand(commandTakePhoto, device, receiverTake);
                });
                string output = receiverTake.ToString();
                txtOutput.AppendText("拍照命令已发送。" + Environment.NewLine + output + Environment.NewLine);
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("拍照失败：" + ex.Message + Environment.NewLine);
            }
        }

        /// <summary>
        /// 双击照片列表中的项后，从设备拉取照片并在本地打开
        /// </summary>
        private async void lbPhotos_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lbPhotos.SelectedItem == null)
            {
                return;
            }

            string fileName = lbPhotos.SelectedItem.ToString();
            if (cbDevices.SelectedItem == null)
            {
                MessageBox.Show("请先选择一个设备。");
                return;
            }
            string serial = cbDevices.SelectedItem.ToString();
            DeviceData device = devices.FirstOrDefault(d => d.Serial == serial);
            if (device == null)
            {
                txtOutput.AppendText("未找到设备 " + serial + Environment.NewLine);
                return;
            }

            // 拼接远程照片的完整路径
            string remotePath = "/sdcard/DCIM/Camera/" + fileName;
            // 定义本地临时文件路径
            string localPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fileName);

            try
            {
                // 使用 SyncService 将远程文件拉取到本地
                using (SyncService service = new SyncService(device))
                {
                    using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write))
                    {
                        await Task.Run(() =>
                        {
                            service.Pull(remotePath, fs, null, false);
                        });
                    }
                }
                txtOutput.AppendText("照片已下载到: " + localPath + Environment.NewLine);
                // 调用系统默认程序打开该文件
                Process.Start(new ProcessStartInfo
                {
                    FileName = localPath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                txtOutput.AppendText("打开照片失败：" + ex.Message + Environment.NewLine);
            }
        }

        /// <summary>
        /// 刷抖音功能：遍历所有已连接设备，对每个设备并行执行
        /// 自动化操作：启动抖音 -> 打开搜索 -> 搜索关键词 -> 点赞、评论、滑动至下一视频
        /// </summary>
        /// <summary>
        /// 刷抖音功能：遍历所有已连接设备，对每个设备并行执行自动化操作。
        /// 操作包括：启动抖音 -> 打开搜索 -> 输入关键词 -> 点赞、评论 -> 滑动到下一视频。
        /// </summary>
        private void btnDouyin_Click(object sender, RoutedEventArgs e)
        {
            // 如果已有刷抖音任务正在进行，先取消后重新启动
            if (douyinCts != null)
            {
                douyinCts.Cancel();
            }
            douyinCts = new CancellationTokenSource();
            CancellationToken token = douyinCts.Token;

            string keyword = "搞笑";
            if (devices == null || devices.Count == 0)
            {
                MessageBox.Show("没有设备，请先刷新设备列表。");
                return;
            }

            foreach (var device in devices)
            {
                // 为每个设备启动独立任务进行操作
                Task.Run(async () =>
                {
                    try
                    {
                        var deviceClient = new DeviceClient(client, device);
                        var receiver = new ConsoleOutputReceiver();
                        // 1. 启动抖音应用
                        client.ExecuteRemoteCommand("am start -n com.ss.android.ugc.aweme/.splash.SplashActivity", device, receiver);
                        AppendOutput(device.Serial + ": 启动抖音");
                        await Task.Delay(5000, token);

                        // 2. 模拟点击搜索区域（坐标示例，需要根据设备调整）
                        client.ExecuteRemoteCommand("input tap 1005 160", device, receiver);
                        AppendOutput(device.Serial + ": 打开搜索框");
                        await Task.Delay(1000, token);

                        // 3. 输入搜索关键词并提交
                        // 原始中文文本
                        client.ExecuteRemoteCommand($"am broadcast -a ADB_INPUT_TEXT --es msg '搞笑'", device, receiver);
                        await Task.Delay(1000, token);
                        client.ExecuteRemoteCommand("input keyevent 66", device, receiver); // 提交搜索
                        AppendOutput(device.Serial + ": 搜索关键词：" + keyword);
                        await Task.Delay(4000, token);
                        client.ExecuteRemoteCommand("input tap 290 283", device, receiver);
                        AppendOutput(device.Serial + ":切换到视频");
                        await Task.Delay(4000, token);
                        client.ExecuteRemoteCommand("input tap 250 761", device, receiver);
                        AppendOutput(device.Serial + ":点击第一个视频");
                        await Task.Delay(4000, token);
                        // 4. 循环模拟点赞、评论以及滑动操作
                        for (int i = 0; i < 3; i++)
                        {
                            token.ThrowIfCancellationRequested();

                            // 模拟点赞操作（示例坐标，需要调整）
                            client.ExecuteRemoteCommand("input tap 300 600", device, receiver);
                            AppendOutput(device.Serial + ": 第" + (i + 1) + "个视频点赞");
                            await Task.Delay(1000, token);

                            // 模拟评论操作（示例坐标）
                            client.ExecuteRemoteCommand("input tap 350 600", device, receiver);
                            AppendOutput(device.Serial + ": 第" + (i + 1) + "个视频评论");
                            await Task.Delay(1000, token);

                            // 模拟向上滑动切换到下一个视频
                            client.ExecuteRemoteCommand("input swipe 300 800 300 400", device, receiver);
                            AppendOutput(device.Serial + ": 切换到第" + (i + 2) + "个视频");
                            await Task.Delay(3000, token);
                        }
                        AppendOutput(device.Serial + ": 本次刷抖音任务结束。");
                    }
                    catch (OperationCanceledException)
                    {
                        AppendOutput(device.Serial + ": 刷抖音任务已被取消。");
                    }
                    catch (Exception ex)
                    {
                        AppendOutput(device.Serial + ": 刷抖音失败：" + ex.Message);
                    }
                }, token);
            }
        }
        /// <summary>
        /// 刷抖音功能：遍历所有已连接设备，对每个设备并行执行
        /// 自动化操作：启动抖音 -> 打开搜索 -> 搜索关键词 -> 点赞、评论、滑动至下一视频
        /// </summary>
        /// <summary>
        /// 刷抖音功能：遍历所有已连接设备，对每个设备并行执行自动化操作。
        /// 操作包括：启动抖音 -> 打开搜索 -> 输入关键词 -> 点赞、评论 -> 滑动到下一视频。
        /// </summary>
        private void btnEasyDouyin_Click(object sender, RoutedEventArgs e)
        {
            // 如果已有刷抖音任务正在进行，先取消后重新启动
            if (douyinCts != null)
            {
                douyinCts.Cancel();
            }
            douyinCts = new CancellationTokenSource();
            CancellationToken token = douyinCts.Token;

            if (devices == null || devices.Count == 0)
            {
                MessageBox.Show("没有设备，请先刷新设备列表。");
                return;
            }

            foreach (var device in devices)
            {
                // 为每个设备启动独立任务进行操作
                Task.Run(async () =>
                {
                    try
                    {
                        var deviceClient = new DeviceClient(client, device);
                        var receiver = new ConsoleOutputReceiver();
                       
                        await Task.Delay(4000, token);
                        // 4. 循环模拟点赞、评论以及滑动操作
                        for (int i = 0; i < 30; i++)
                        {
                            token.ThrowIfCancellationRequested();
                            // 模拟向上滑动切换到下一个视频
                            client.ExecuteRemoteCommand("input swipe 300 800 300 400", device, receiver);
                            AppendOutput(device.Serial + ": 切换到第" + (i + 2) + "个视频");
                            await Task.Delay(10000, token);
                        }
                        AppendOutput(device.Serial + ": 本次刷抖音任务结束。");
                    }
                    catch (OperationCanceledException)
                    {
                        AppendOutput(device.Serial + ": 刷抖音任务已被取消。");
                    }
                    catch (Exception ex)
                    {
                        AppendOutput(device.Serial + ": 刷抖音失败：" + ex.Message);
                    }
                }, token);
            }
        }

        /// <summary>
        /// 停止刷抖音功能，取消所有刷抖音任务
        /// </summary>
        private void btnStopDouyin_Click(object sender, RoutedEventArgs e)
        {
            if (douyinCts != null && !douyinCts.IsCancellationRequested)
            {
                douyinCts.Cancel();
                AppendOutput("所有刷抖音任务已请求取消。");
            }
        }
        /// <summary>
        /// 帮助在 UI 中线程安全地添加输出信息
        /// </summary>
        /// <param name="msg"></param>
        private void AppendOutput(string msg)
        {
            Dispatcher.Invoke(() =>
            {
                txtOutput.AppendText(msg + Environment.NewLine);
            });
        }

        private void btnOcr_Click(object sender, RoutedEventArgs e)
        {
            // 初始化OCR引擎
            OCRModelConfig config = null; // 使用默认模型
            OCRParameter oCRParameter = new OCRParameter();

            // 创建OCR引擎
            PaddleOCREngine engine = new PaddleOCREngine(config, oCRParameter);

            // 识别图片
            OCRResult result = engine.DetectText("D:\\aaaa.jpg");

            // 输出识别结果
            if (result != null)
            {
                AppendOutput("识别文本:");
                AppendOutput(result.Text);
            }

            // 释放资源
            engine.Dispose();
        }
    }
}
